"use strict";
const BaseController = require("../base");

// 定义创建接口的请求参数规则
const getAttrListRule = {
  category1Id: "string",
  category2Id: "string",
  category3Id: "string",
};

const saveAttrRule = {
  attrName: "string",
  attrValueList: {
    type: "array",
    itemType: "object",
    required: true,
    rule: {
      valueName: "string",
    },
  },
  categoryLevel: "number",
  categoryId: "string",
};

const updateAttrRule = {
  attrName: "string",
  attrValueList: {
    type: "array",
    itemType: "object",
    required: true,
    rule: {
      valueName: "string",
    },
  },
  categoryLevel: "number",
  categoryId: "string",
  id: "string",
};

const removeAttrRule = {
  id: "string",
};

class AttrsController extends BaseController {
  async getAttrList() {
    const ctx = this.ctx;
    // 如果参数校验未通过，将会抛出一个 status = 422 的异常
    ctx.validate(getAttrListRule, ctx.params);
    const data = await ctx.service.product.attrs.getAttrList(ctx.params);
    this.success(data);
  }
  async saveAttr() {
    const ctx = this.ctx;
    // 校验参数是否符合我们预期的格式
    // 如果参数校验未通过，将会抛出一个 status = 422 的异常
    const body = ctx.request.body;
    ctx.validate(saveAttrRule, body);
    const data = await ctx.service.product.attrs.saveAttr(body);
    this.success(data);
  }
  async updateAttr() {
    const ctx = this.ctx;
    const body = ctx.request.body;
    ctx.validate(updateAttrRule, body);
    const success = await ctx.service.product.attrs.updateAttr(body);
    if (success) {
      this.success();
    } else {
      this.fail();
    }
  }
  async removeAttr() {
    const ctx = this.ctx;
    // 校验参数是否符合我们预期的格式
    const id = ctx.params.id;
    // 如果参数校验未通过，将会抛出一个 status = 422 的异常
    ctx.validate(removeAttrRule, {
      id,
    });
    const success = await ctx.service.product.attrs.removeAttr(id);
    if (success) {
      this.success();
    } else {
      this.fail();
    }
  }
}

module.exports = AttrsController;
